package io.codegeneratetool.web.controllers.opt.base;

import io.codegeneratetool.impl.entity.dbutil.TableInfoGetter;
import io.codegeneratetool.impl.entity.dbutil.TableInfoGetterFactory;
import io.codegeneratetool.util.StringUtils;
import io.codegeneratetool.web.common.PageRequest;
import io.codegeneratetool.web.common.PagerResult;
import io.codegeneratetool.web.common.ResultTemplate;
import io.codegeneratetool.web.entity.DBConnection;
import io.codegeneratetool.web.service.DBConnectionService;
import io.codegeneratetool.web.service.JDBCTemplateFactory;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

/** 数据库配置维护
 * @author jifsu
 *
 */
@Controller
@RequestMapping("/opt/base/db")
public class DbController {

	
	@Autowired
	private DBConnectionService dbConnectionService;
	
	@RequestMapping("list")
	public void list(HttpServletRequest request,Model view){
	
		 
	}
	@SuppressWarnings("rawtypes")
	@RequestMapping("listData")
	@ResponseBody
	public PagerResult listData(HttpServletRequest request,Model view,PageRequest pageRequest){ 
		if(pageRequest==null){
			pageRequest=new PageRequest();
		}
		 PagerResult findAll = dbConnectionService.findAll(pageRequest);
		return findAll;
	}
	
	@RequestMapping("savePage")
	public void savePage(HttpServletRequest request,Model view,@RequestParam(required=false) String id){
		DBConnection connection = null; 
		if(!StringUtils.isNullOrEmpty(id)){
			connection = dbConnectionService.findById(id);
			
		 }else{
			 connection = new DBConnection();
		 }
		view.addAttribute("entity", connection);
	}
	
	

	@RequestMapping("save")
	@ResponseBody
	public String save(HttpServletRequest request,Model view,DBConnection dbConnection ){ 
		dbConnectionService.createOrUpdateEntity(dbConnection);
		return "<script> parent.reload();</script>";
	}
	
	@RequestMapping("del")
	@ResponseBody
	public ResultTemplate del(String id){
		ResultTemplate resultTemplate = ResultTemplate.createSuccessResult(dbConnectionService.del(id));
		
		return resultTemplate.setMessage("删除成功");
	}
	
	
	
	@RequestMapping("getAllTables")
	@ResponseBody
	public List<String> getAllTables(String id) throws Exception{
		DBConnection conn = dbConnectionService.findById(id);
		TableInfoGetter getter =  TableInfoGetterFactory.get(conn.getDrivername());
		getter.setCustomerJdbcTemplate(JDBCTemplateFactory.createJdbcTemplate(conn));
		return getter.getAllTables();
	}
	
	
	
	
	
	
}
